<?php

namespace App\Exceptions;

use Exception;
use Illuminate\Validation\ValidationException;
use Illuminate\Auth\Access\AuthorizationException;
use Illuminate\Database\Eloquent\ModelNotFoundException;
use Laravel\Lumen\Exceptions\Handler as ExceptionHandler;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends ExceptionHandler
{
    /**
     * A list of the exception types that should not be reported.
     *
     * @var array
     */
    protected $dontReport = [
        AuthorizationException::class,
        HttpException::class,
        ModelNotFoundException::class,
        ValidationException::class,
        BasicException::class,
    ];

    /**
     * 重构日志记录方法
     */
    public function report(Exception $exception)
    {
        // if (app()->bound('sentry') && $this->shouldReport($exception)) {
        //     app('sentry')->captureException($exception);
        // }

        parent::report($exception);
    }

    /**
     * 重构异常上报方法
     */
    public function render($request, Exception $exception)
    {
        //      验参错误
        if ($exception instanceof ValidationException) {
            $msg = '';
            is_array($exception->getResponse()->original) && $msg = end($exception->getResponse()->original);
            is_array($msg) && $msg = end($msg);
            return response()->json(['code' => $exception->getCode(), 'message' => $msg]);
        }

        if($exception instanceof BasicException) {
            $json_data = ['code'=>$exception->getCode(),'message'=>$exception->getMessage()];
            if (!empty($exception->getParams())) {
                $json_data['errordata'] = $exception->getParams();
            }
            return response()->json($json_data);
        } else {
            $rendered = parent::render($request, $exception);
            if(env('APP_ENV') !== 'production') {
                // return response()->json(['code'=>$exception->getCode(),'message'=>$exception->getMessage()]);
                return $rendered;
            } else {
                return response()->json(['code'=>520,'message'=>'o(╯□╰)o哎呀,服务器爆炸了~']);
            }
        }
    }
}
